<template>
  <div :id="playerId" class="prism-player" :style="playStyle" />
</template>

<script>
export default {
  name: 'Aliplayer',
  props: {
    playStyle: {
      type: String,
      default: ''
    },
    aliplayerSdkPath: {
      // Aliplayer 代码的路径
      type: String,
      default: 'https://g.alicdn.com/de/prismplayer/2.8.2/aliplayer-h5-min.js'
    },
    autoplay: {
      type: Boolean,
      default: false
    },
    isLive: {
      type: Boolean,
      default: false
    },
    playsinline: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '280px'
    },
    controlBarVisibility: {
      type: String,
      default: 'always'
    },
    vid: {
      type: String,
      default: ''
    },
    playauth: {
      type: String,
      default: ''
    },
    source: {
      type: String,
      default: ''
    },
    cover: {
      type: String,
      default: ''
    },
    format: {
      type: String,
      default: 'm3u8'
    },
    x5VideoPosition: {
      type: String,
      default: 'top'
    },
    x5Type: {
      type: String,
      default: 'h5'
    },
    x5Fullscreen: {
      type: Boolean,
      default: false
    },
    x5Orientation: {
      type: Number,
      default: 2
    },
    autoPlayDelay: {
      type: Number,
      default: 0
    },
    autoPlayDelayDisplayText: {
      type: String
    }
  },
  data() {
    return {
      playerId: 'aliplayer_' + Math.random() * 100000000000000000,
      scriptTagStatus: 0,
      instance: null
    }
  },
  beforeDestroy() {
    console.log('阿里播放器销毁')
    this.pause()
    this.instance.stop()
    this.instance = null
  },
  // created() {
  //   if (window.Aliplayer !== undefined) {
  //     // 如果全局对象存在，说明编辑器代码已经初始化完成，直接加载编辑器
  //     this.scriptTagStatus = 2
  //     this.initAliplayer(1)
  //   } else {
  //     // 如果全局对象不存在，说明编辑器代码还没有加载完成，需要加载编辑器代码
  //     this.insertScriptTag()
  //   }
  // },
  mounted() {
    if (window.Aliplayer !== undefined) {
      // 如果全局对象存在，说明编辑器代码已经初始化完成，直接加载编辑器
      this.scriptTagStatus = 2
      this.initAliplayer(2)
    } else {
      // 如果全局对象不存在，说明编辑器代码还没有加载完成，需要加载编辑器代码
      this.insertScriptTag()
    }
  },
  methods: {
    insertScriptTag() {
      const that = this
      let playerScriptTag = document.getElementById('playerScriptTag')
      // 如果这个tag不存在，则生成相关代码tag以加载代码
      if (playerScriptTag === null) {
        playerScriptTag = document.createElement('script')
        playerScriptTag.type = 'text/javascript'
        playerScriptTag.src = this.aliplayerSdkPath
        playerScriptTag.id = 'playerScriptTag'
        const s = document.getElementsByTagName('head')[0]
        s.appendChild(playerScriptTag)
      }
      if (playerScriptTag.loaded) {
        that.scriptTagStatus++
      } else {
        playerScriptTag.addEventListener('load', () => {
          that.scriptTagStatus++
          playerScriptTag.loaded = true
          that.initAliplayer(3)
        })
      }
      that.initAliplayer(4)
    },
    initAliplayer(num) {
      console.log('initAliplayer' + num)
      const that = this
      // scriptTagStatus 为 2 的时候，说明两个必需引入的 js 文件都已经被引入，且加载完成
      if (that.scriptTagStatus === 2 && that.instance === null) {
        // Vue 异步执行 DOM 更新，这样一来代码执行到这里的时候可能 template 里面的 script 标签还没真正创建
        // 所以，我们只能在 nextTick 里面初始化 Aliplayer
        that.$nextTick(() => {
          that.instance = window.Aliplayer({
            'id': that.playerId,
            'autoplay': that.autoplay,
            'isLive': that.isLive,
            'playsinline': that.playsinline,
            'format': that.format,
            'width': that.width,
            'height': that.height,
            'controlBarVisibility': that.controlBarVisibility,
            'useH5Prism': true,
            'vid': that.vid,
            'playauth': that.playauth,
            'source': that.source,
            'cover': that.cover,
            'x5_video_position': that.x5_video_position,
            'x5_type': that.x5_type,
            'x5_fullscreen': that.x5_fullscreen,
            'x5_orientation': that.x5_orientation,
            'autoPlayDelay': that.autoPlayDelay,
            'autoPlayDelayDisplayText': that.autoPlayDelayDisplayText,
            'extraInfo': {
              'liveRetry': 1,
              'crossOrigin': 'anonymous'
            },
            'skinLayout': [
              {
                'name': 'bigPlayButton',
                'align': 'blabs',
                'x': 30,
                'y': 80
              },
              {
                'name': 'errorDisplay',
                'align': 'tlabs',
                'x': 0,
                'y': 0
              },
              {
                'name': 'infoDisplay'
              },
              {
                'name': 'controlBar',
                'align': 'blabs',
                'x': 0,
                'y': 0,
                'children': [
                  {
                    'name': 'liveDisplay',
                    'align': 'tlabs',
                    'x': 15,
                    'y': 6
                  },
                  {
                    'name': 'fullScreenButton',
                    'align': 'tr',
                    'x': 10,
                    'y': 10
                  },
                  {
                    'name': 'volume',
                    'align': 'tr',
                    'x': 5,
                    'y': 10
                  },
                  {
                    'name': 'snapshot',
                    'align': 'tr',
                    'x': 10,
                    'y': 12
                  }
                ]
              }
            ]
          })
          // 绑定事件，当 AliPlayer 初始化完成后，将编辑器实例通过自定义的 ready 事件交出去
          that.instance.on('ready', () => {
            this.$emit('ready', that.instance)
          })
          that.instance.on('play', () => {
            // console.log(that.source)
            this.$emit('play', that.instance)
          })
          that.instance.on('pause', () => {
            this.$emit('pause', that.instance)
          })
          that.instance.on('ended', () => {
            this.$emit('ended', that.instance)
          })
          that.instance.on('liveStreamStop', () => {
            this.$emit('liveStreamStop', that.instance)
          })
          that.instance.on('m3u8Retry', () => {
            this.$emit('m3u8Retry', that.instance)
          })
          that.instance.on('hideBar', () => {
            this.$emit('hideBar', that.instance)
          })
          that.instance.on('waiting', () => {
            this.$emit('waiting', that.instance)
          })
          that.instance.on('snapshoted', () => {
            this.$emit('snapshoted', that.instance)
          })
        })
      }
    },
    /**
       * 播放视频
       */
    play() {
      this.instance.play()
    },
    /**
       * 暂停视频
       */
    pause() {
      this.instance.pause()
    },
    /**
       * 重播视频
       */
    replay() {
      this.instance.replay()
    },
    /**
       * 跳转到某个时刻进行播放
       * @argument time 的单位为秒
       */
    seek(time) {
      this.instance.seek(time)
    },
    /**
       * 获取当前时间 单位秒
       */
    getCurrentTime() {
      return this.instance.getCurrentTime()
    },
    /**
       *获取视频总时长，返回的单位为秒
       * @returns 返回的单位为秒
       */
    getDuration() {
      return this.instance.getDuration()
    },
    /**
       获取当前的音量，返回值为0-1的实数ios和部分android会失效
       */
    getVolume() {
      return this.instance.getVolume()
    },
    /**
       设置音量，vol为0-1的实数，ios和部分android会失效
       */
    setVolume(vol) {
      this.instance.setVolume(vol)
    },
    /**
       *直接播放视频url，time为可选值（单位秒）目前只支持同种格式（mp4/flv/m3u8）之间切换暂不支持直播rtmp流切换
       *@argument url 视频地址
       *@argument time 跳转到多少秒
       */
    loadByUrl(url, time) {
      this.instance.loadByUrl(url, time)
    },
    /**
       * 设置播放速度
       *@argument speed 速度
       */
    setSpeed(speed) {
      this.instance.setSpeed(speed)
    },
    /**
       * 设置播放器大小w,h可分别为400px像素或60%百分比chrome浏览器下flash播放器分别不能小于397x297
       *@argument w 播放器宽度
       *@argument h 播放器高度
       */
    setPlayerSize(w, h) {
      this.instance.setPlayerSize(w, h)
    },
    /**
       * 目前只支持HTML5界面上的重载功能,暂不支持直播rtmp流切换m3u8）之间切换,暂不支持直播rtmp流切换
       *@argument vid 视频id
       *@argument playauth 播放凭证
       */
    reloaduserPlayInfoAndVidRequestMts(vid, playauth) {
      this.instance.reloaduserPlayInfoAndVidRequestMts(vid, playauth)
    }
  }
}
</script>

<style>
  @import url(https://g.alicdn.com/de/prismplayer/2.8.2/skins/default/aliplayer-min.css);
</style>
